﻿
using System;
using System.Collections.Generic;
using System.Text;

namespace REVISIONMAX30.DataObjects
{
    public class Group : DataObjectBase
    {
        public Group()
        {
        }

        public Group(string pGroupName)
        {
            this.GroupName = pGroupName;
            this.BackUpDirectory = @".\batchtemp\";

            this.ConnectionStringList = new List<ConnectionString>();
            this.SourceDirectoryList = new List<SourceDirectory>();
            this.SQLItemList = new List<SQLItem>();
        }

        public string GroupName { get; set; }
        public int CurrentRevision { get; set; }
        public string BackUpDirectory { get; set; }
        public List<ConnectionString> ConnectionStringList { get; set; }
        public List<SourceDirectory> SourceDirectoryList { get; set; }
        public List<SQLItem> SQLItemList { get; set; }

        public Frame.FrResultType DumpDBsToBackUp()
        {
            var tFrResult = new Frame.FrResultType();

            foreach (var tConnectionString in this.ConnectionStringList)
            {
                if (!tConnectionString.Name.Equals("temp", StringComparison.CurrentCultureIgnoreCase))
                {
                    var tFrSubResult = tConnectionString.TestConnection();

                    if (!tFrSubResult.HasErrorOrCritical())
                    {
                        var tConnectionStringBuilder = tConnectionString.ConnectionStringBuilder;

                        if (!System.IO.Directory.Exists(this.BackUpDirectory))
                        {
                            System.IO.Directory.CreateDirectory(this.BackUpDirectory);
                        }

                        string tBackUpFileName = string.Format("{0}{1}_{2}_{3}.sql", new object[] { this.BackUpDirectory, this.CurrentRevision, string.Format("{0:00}", this.ConnectionStringList.IndexOf(tConnectionString)), tConnectionStringBuilder.Database });

                        if (System.IO.File.Exists(tBackUpFileName))
                        {
                            System.IO.File.Delete(tBackUpFileName);
                        }

                        tFrSubResult = MySQLDBHandler.ExecuteDumpDBWithMySQLBatch(tConnectionStringBuilder.UserID, tConnectionStringBuilder.Password, tConnectionStringBuilder.Database, tBackUpFileName, tConnectionString.MySQLBatchPath);

                        if (tFrSubResult.HasErrorOrCritical())
                        {
                            tFrResult.AddResult(tFrSubResult);
                        }
                    }
                    else
                    {
                        tFrResult.AddResult(tFrSubResult);
                    }
                }
            }

            return tFrResult;
        }


    }
}

